package com.tmpt.utils.report;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import com.tmpt.utils.DateTool;
import com.tmptSource.dto.OwrDoubleTaskPairDto;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Helen
 * @version 1.0
 * @date 2020/1/17 23:23
 * @Description:
 */
public class PdfUtils {

    /**
     * 双随机报表-单张
     * @param title
     * @param owrDoubleTaskPairDto
     * @param response
     * @throws IOException
     */
    public static void downloadReport4DoubleRandomPDF(String title , OwrDoubleTaskPairDto owrDoubleTaskPairDto, HttpServletResponse response) throws IOException {
		/*String templatePath ="d:/Report/template4Random.pdf";
		// 生成的新文件路径
		String newPDFPath = "d:/Report/123123.pdf";*/
        String templatePath ="/template/template4Random.pdf";
//		String templatePath ="d:/Report/template4Random.pdf";//本地测试

        PdfReader reader;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        int owrType = Integer.parseInt(owrDoubleTaskPairDto.getOwrType());
        String str1 = "跨门经营（    ）";
        String str2 = "";
        if(owrType==2) {
            str2 = "餐厨垃圾、废弃油脂产生单位（  Y ）";
        }else {
            str2 = "餐厨垃圾、废弃油脂产生单位（    ）";
        }
        String str3 = "生活垃圾（   ）";
        String str4 = "";
        if(owrType==1) {
            str4 = "建筑工地、中转码头（  Y  )";
        }else{
            str4 = "建筑工地、中转码头（     )";
        }
        String str5 = owrDoubleTaskPairDto.getEntityName();
        String str6 = owrDoubleTaskPairDto.getImproveRequied();
        String str7 = owrDoubleTaskPairDto.getDealIssueContent();
        String str8 = owrDoubleTaskPairDto.getDealResult();
        String str9 = owrDoubleTaskPairDto.getUserName();
        try {
            //out = new FileOutputStream(newPDFPath);// 输出流
            //InputStream inputStream = ExcelUtils.class.getResourceAsStream("/b.pdf");
            //ObjectInputStream oos = new ObjectInputStream(inputStream);
            //System.out.println(inputStream.available());
            reader = new PdfReader(templatePath);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            //inputStream.close();
            String dealTimeStr = "";
            try{
                dealTimeStr = DateTool.date2String(DateTool.string2DateForAnyFormat(owrDoubleTaskPairDto.getDealTime(),"yyyy-MM-dd"),"yyyy年MM月dd日");
            }catch (Exception e){}
            String[] str = { dealTimeStr, str1, str2, str3, str4, str5, str6, str7 , str8, str9};
            int i = 0;
            java.util.Iterator<String> it = form.getFields().keySet().iterator();
            while (it.hasNext()) {
                String name = it.next().toString();
                String value = str[i++];
                form.setField(name,value);
            }

            stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
            stamper.close();

            String fileName = title+".pdf";


            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/pdf");
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename="+fileName);

            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, outputStream);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();
            outputStream.flush();
            outputStream.close();
            //inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }

    /**
     * 双随机任务报表-批量
     * @param title
     * @param list
     * @param response
     * @throws IOException
     */
    public static void downloadReport4DoubleRandomPDFBatch(String title , List<OwrDoubleTaskPairDto> list, HttpServletResponse response) throws IOException {
        String templatePath ="/template/template4Random.pdf";
        PdfReader reader;
        ByteArrayOutputStream bos;
        PdfStamper stamper;

        try {
            List<PdfReader> listResult = new ArrayList();
            if(list.size()>0){
                for(int i=0; i<list.size(); i++){
                    // 读取pdf模板
                    reader = new PdfReader(templatePath);
                    bos = new ByteArrayOutputStream();
                    stamper = new PdfStamper(reader, bos);
                    AcroFields form = stamper.getAcroFields();
                    OwrDoubleTaskPairDto owrDoubleTaskPairDto = list.get(i);
                    int owrType = Integer.parseInt(owrDoubleTaskPairDto.getOwrType());
                    String str1 = "跨门经营（    ）";
                    String str2 = "";
                    if(owrType==2) {
                        str2 = "餐厨垃圾、废弃油脂产生单位（  Y ）";
                    }else {
                        str2 = "餐厨垃圾、废弃油脂产生单位（    ）";
                    }
                    String str3 = "生活垃圾（   ）";
                    String str4 = "";
                    if(owrType==1) {
                        str4 = "建筑工地、中转码头（  Y  )";
                    }else{
                        str4 = "建筑工地、中转码头（     )";
                    }
                    String str5 = owrDoubleTaskPairDto.getEntityName();
                    String str6 = owrDoubleTaskPairDto.getImproveRequied();
                    String str7 = owrDoubleTaskPairDto.getDealIssueContent();
                    String str8 = owrDoubleTaskPairDto.getDealResult();
                    String str9 = owrDoubleTaskPairDto.getUserName();

                    String dealTimeStr = "";
                    try{
                        dealTimeStr = DateTool.date2String(DateTool.string2DateForAnyFormat(owrDoubleTaskPairDto.getDealTime(),"yyyy-MM-dd"),"yyyy年MM月dd日");
                    }catch (Exception e){}
                    String[] str = { dealTimeStr, str1, str2, str3, str4, str5, str6, str7 , str8, str9};
                    int j = 0;
                    java.util.Iterator<String> it = form.getFields().keySet().iterator();
                    while (it.hasNext()) {
                        String name = it.next().toString();
                        String value = str[j++];
                        form.setField(name,value);
                    }

                    // 如果为false那么生成的PDF文件还能编辑，一定要设为true
                    stamper.setFormFlattening(true);
                    stamper.close();
                    PdfReader pdfReader = new PdfReader(bos.toByteArray());
                    System.out.println("bos:"+bos);
                    listResult.add(pdfReader);
                }
                String fileName = title+".pdf";

                OutputStream outputStream = response.getOutputStream();
                response.setContentType("application/pdf");
                fileName = URLEncoder.encode(fileName, "UTF-8");
                response.addHeader("Content-Disposition", "attachment;filename="+fileName);

                Document document = new Document();
                PdfCopy copy = new PdfCopy(document, outputStream);
                document.open();
                for(int k=0; k<list.size();k++){
                    PdfReader pdfReader = listResult.get(k);
                    //下一页
                    document.newPage();
                    copy.addDocument(pdfReader);
                }
                document.close();
                outputStream.flush();
                outputStream.close();
            }else{
                // 读取pdf模板
                reader = new PdfReader(templatePath);
                bos = new ByteArrayOutputStream();
                stamper = new PdfStamper(reader, bos);
                AcroFields form = stamper.getAcroFields();
                String str1 = "";
                String str2 = "";
                String str3 = "";
                String str4 = "";
                String str5 = "";
                String str6 = "";
                String str7 = "";
                String str8 = "";
                String str9 = "";

                String dealTimeStr = "";
                dealTimeStr = "";
                String[] str = { dealTimeStr, str1, str2, str3, str4, str5, str6, str7 , str8, str9};
                int j = 0;
                java.util.Iterator<String> it = form.getFields().keySet().iterator();
                while (it.hasNext()) {
                    String name = it.next().toString();
                    String value = str[j++];
                    form.setField(name,value);
                }

                // 如果为false那么生成的PDF文件还能编辑，一定要设为true
                stamper.setFormFlattening(true);
                stamper.close();
                PdfReader pdfReader = new PdfReader(bos.toByteArray());
                System.out.println("bos:"+bos);
                listResult.add(pdfReader);
                String fileName = title+".pdf";

                OutputStream outputStream = response.getOutputStream();
                response.setContentType("application/pdf");
                fileName = URLEncoder.encode(fileName, "UTF-8");
                response.addHeader("Content-Disposition", "attachment;filename="+fileName);

                Document document = new Document();
                PdfCopy copy = new PdfCopy(document, outputStream);
                document.open();
                document.newPage();
                copy.addDocument(pdfReader);
                document.close();
                outputStream.flush();
                outputStream.close();
            }

        }catch (DocumentException e) {
            e.printStackTrace();
        }

    }

}
